﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;

namespace shuju_jiange
{
    public partial class Form3 : Form
    {
        private const string strOrderTimeFileName = "OrderTime.dat";
        public Form3()
        {
            InitializeComponent();
        }
        List<String> g_strlist = new List<String>();

        private void button1_Click(object sender, EventArgs e)
        {
            openFileDialog1.Filter = "csv文件|*.csv";
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String file = openFileDialog1.FileName;
                label1.Text = "文件:" + file;
                FileStream fsr = new FileStream(file, FileMode.Open);
                StreamReader sr = new StreamReader(fsr, Encoding.Default);
                g_strlist.Clear();
                String l;
                sr.ReadLine();
                while ((l = sr.ReadLine()) != null) 
                {
                    l = l.Replace(",","").Replace(" ","");
                    if (l.Contains("*") || l.Length != 3) continue;
                    g_strlist.Add(l);
                }
                sr.Close();
                fsr.Close();
                richTextBox1.Text = String.Join(" ", g_strlist);
            }
        }

        private void button3_Click(object sender, EventArgs e)
        {
            g_daorulist = richTextBox1.SelectedText.Trim().Split(' ').ToList();
            g_text_str = richTextBox1.SelectedText.Trim().Replace(' ', '-');
            daoru_process();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            // 导出
            saveFileDialog1.Filter = "csv文件|*.csv";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                String file = saveFileDialog1.FileName;
                File.Delete(file);
                FileStream fsw = new FileStream(file, FileMode.Create);
                StreamWriter sw = new StreamWriter(fsw, Encoding.Default);
                sw.WriteLine("*,*,*");
                for (int i = 0; i < dataGridView1.Rows.Count; i++)
                {
                	String t = dataGridView1.Rows[i].Cells[0].Value.ToString().Trim();
                    String l = "";
                    for (int j = 0; j < t.Length; j++)
                        l += t.Substring(j, 1) + ",";
                    l = l.Trim(',');
                    int n = Convert.ToInt32("0" + dataGridView1.Rows[i].Cells[1].Value.ToString().Trim());
                    for (int j = 0; j < n;j++)
                        sw.WriteLine(l);
                }
                sw.Close();
                fsw.Close();
                MessageBox.Show("导出成功!");
            }

        }

        private int get_num(List<String> list, String s,ref int jiange)
        {
            int c = 0,  start = -1, end = -1;
            for (int i = 0; i < list.Count; i++)
            {
                if (s == list[i])
                {
                    c += 1;
                    if (start < 0) start = i;
                    end = i;
                    pointlist.Add(new mypoint(i,s));
                }
            }
            jiange = end - start;
            return c;
        }
        private List<String> g_daorulist = null;
        private List<String> g_daorufillist = new List<String>();
        private DataTable g_dtab1 = new DataTable();
        //private DataTable g_dtabdel = new DataTable();
        private String g_del_text = "";
        private String g_text_str = "";
        private List<mypoint> pointlist = new List<mypoint>();
        private void daoru_process()
        {
            pointlist.Clear();

            if (g_daorulist == null) return;
            int ct,jg=0,sj=0,st=0;
            String[] its = g_text_str.Replace(" ","").Trim().Trim('-').Split('-');
            g_daorufillist.Clear();
            foreach (String s in its)
            {
                if (g_daorufillist.Contains(s)) continue;
                g_daorufillist.Add(s);
            }
            g_dtab1.Rows.Clear();
            for (int i = 0; i < g_daorufillist.Count; i++)
            {
                if (g_daorufillist[i].Trim() == "") continue;
                ct = get_num(g_daorulist,g_daorufillist[i],ref jg);
                sj += jg;
                if(ct > 1)
                    st += ct-1;
                DataRow row = g_dtab1.Rows.Add();
                row[0] = g_daorufillist[i];
                row[1] = ct;
                row[2] = ct > 1 ? jg / (ct-1) : 0;
            }
            int pj = 0;
            pj = st > 0 ? sj / st : 0;
            label3.Text = "总平均间隔:" + pj;
            dataGridView1.DataSource = g_dtab1;
            tongji_pinjun();
             
            g_del_text = "";
        }
        private void delete_point_list(String s)
        {
            int v = Convert.ToInt32("0" + s.Trim());
            for (int i = pointlist.Count - 1; i > -1; i--)
            {

                if (pointlist[i].y == v)
                {
                    pointlist.RemoveAt(i);
                }
            }
        }
        private void tongji_pinjun()
        {
            int s1 = 0, s2 = 0, n1, n2;
            for (int i = 0; i < g_dtab1.Rows.Count; i++)
            {
                n1 = Convert.ToInt32("0" + g_dtab1.Rows[i][1].ToString().Trim());
                n2 = Convert.ToInt32("0" + g_dtab1.Rows[i][2].ToString().Trim());

                if (n1 > 1)
                {
                    n1 = n1 -1;
                    s1 += n1;
                    s2 += n1 * n2;
                }
            }
            int z = 0;
            if (s1 > 0) z = s2 / s1;
            label3.Text = "总平均间隔:" + z;
        }

        private void button4_Click(object sender, EventArgs e)
        {
            g_daorulist = richTextBox1.Text.Trim().Split(' ').ToList();
            g_text_str = richTextBox1.Text.Trim().Replace(' ', '-');
            daoru_process();
        }

        private void button5_Click(object sender, EventArgs e)
        {
            g_text_str = textBox1.Text.Trim().Replace(' ', '-');
            daoru_process();
        }

        private void button6_Click(object sender, EventArgs e)
        {
            pointlist.Clear();
            g_dtab1.Rows.Clear();
            dataGridView1.DataSource = g_dtab1;
            tongji_pinjun();
        }

        private void button7_Click(object sender, EventArgs e)
        {
            // xianshi tuxing 
 
            Form2 fm = new Form2(pointlist);
            fm.ShowDialog();
        }

        private void button8_Click(object sender, EventArgs e)
        {
            if (dataGridView1.SelectedRows.Count < 1)
            {
                MessageBox.Show("没有选中任何行!");
                return;
            }
            int idx = dataGridView1.SelectedRows[0].Index;
            delete_point_list(g_dtab1.Rows[idx][0].ToString());
            g_dtab1.Rows.RemoveAt(idx);
            dataGridView1.DataSource = g_dtab1;
            tongji_pinjun();
        }

        private void button9_Click(object sender, EventArgs e)
        {
            String[] its = textBox2.Text.Trim().Replace(' ','-').Split('-');
            foreach (String t in its)
            {
                for (int i = g_dtab1.Rows.Count-1; i >-1 ; i--)
                {
                    if (t == g_dtab1.Rows[i][1].ToString())
                    {
                        
                        g_del_text += g_dtab1.Rows[i][0].ToString() + " ";

                        delete_point_list(g_dtab1.Rows[i][0].ToString());
                        g_dtab1.Rows.RemoveAt(i);
                    }
                }
            }
            dataGridView1.DataSource = g_dtab1;
            tongji_pinjun();

            richTextBox2.Text = g_del_text;
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            g_dtab1.Columns.Clear();
            g_dtab1.Columns.Add("数据");
            g_dtab1.Columns.Add("出现次数");
            g_dtab1.Columns.Add("平均间隔");
            RefreshOrderTime();

        }

        private void richTextBox1_SelectionChanged(object sender, EventArgs e)
        {
            String []t = richTextBox1.SelectedText.Trim().Split(' ');
            int k = t.Length;
            if (t[0] == "") k = 0;
            label4.Text = "选中记录数为:" + k;
        }

        private void button10_Click(object sender, EventArgs e)
        {
            String[] its = textBox3.Text.Trim().Replace(' ','-').Split('-');
            foreach (String t in its)
            {
                for (int i = g_dtab1.Rows.Count - 1; i > -1; i--)
                {
                    if (t == g_dtab1.Rows[i][0].ToString())
                    {
                        g_del_text += g_dtab1.Rows[i][0].ToString()+" ";

                        delete_point_list(g_dtab1.Rows[i][0].ToString());
                        g_dtab1.Rows.RemoveAt(i);
                    }
                }
            }
            dataGridView1.DataSource = g_dtab1;
            tongji_pinjun();

            richTextBox2.Text = g_del_text;
        }

        private void button11_Click(object sender, EventArgs e)
        {
            String[] its= richTextBox1.Text.Trim().Split(' ');
            int start = its.Length - Convert.ToInt32("0"+textBox5.Text.Trim());
            int end = its.Length - Convert.ToInt32("0" + textBox4.Text.Trim());
            String temp = "";
            for (int i = start; i <= end; i++)
            {
                temp += its[i] + " ";
            }
            g_daorulist = temp.Trim().Split(' ').ToList();
            g_text_str = temp.Trim().Replace(' ', '-');
            daoru_process();
        }

        private void button12_Click(object sender, EventArgs e)
        {
            String[] delits = textBox6.Text.Trim().Replace(" ","-").Split('-');
            String content = richTextBox1.Text.Trim();

            foreach (String s in delits)
            {
                String ks = s.Trim();
                if (ks.Length == 3)
                {
                   content = content.Replace(ks, "");
                }
            }
            content = content.Replace("  ", " ");
            richTextBox1.Text = content;
        }

        private void button13_Click(object sender, EventArgs e)
        {
            String filename = Application.StartupPath + "//main_data.txt";

            File.Delete(filename);
            FileStream fs = new FileStream(filename, FileMode.OpenOrCreate);
            StreamWriter sw = new StreamWriter(fs,Encoding.Default);

            sw.WriteLine("序号,次数,第1位,第2位,第3位");
            for (int i = 0; i < dataGridView1.Rows.Count; i++)
            {
            	String z = dataGridView1.Rows[i].Cells[0].Value.ToString();// g_dtab1.Rows[i][0].ToString();
                z = z.PadLeft(3, '0');
                String line = z + ",0,"+z.Substring(0,1)+",1"+z.Substring(1,1)+",2"+z.Substring(2,1);
                sw.WriteLine(line);
            }
            
            sw.Close();
            fs.Close();
            MessageBox.Show("导出成功!");
        }

        private void button14_Click(object sender, EventArgs e)
        {
            daochu_x("pre",checkBox1.Checked);
        }

        private void button15_Click(object sender, EventArgs e)
        {
            daochu_x("next",checkBox1.Checked);
        }

        private void button16_Click(object sender, EventArgs e)
        {
            daochu_x("null",checkBox1.Checked);
        }

        private void daochu_x(String type,bool check)
        {
            String file = "";
            if(check)
            	saveFileDialog1.Filter = "csv文件|*.csv";
            else
	            saveFileDialog1.Filter = "txt文件|*.txt";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                file = saveFileDialog1.FileName;
            }
            else
            {
                return;
            }
            if (File.Exists(file)) File.Delete(file);
            FileStream fsw = new FileStream(file, FileMode.Create);
            StreamWriter sw = new StreamWriter(fsw, Encoding.Default);

            // ------------------------
            String[] its = richTextBox1.Text.Trim().Split(' ');
            int start = its.Length - Convert.ToInt32("0" + textBox5.Text.Trim());
            int end = its.Length - Convert.ToInt32("0" + textBox4.Text.Trim());
            String t = "",s;
            for (int i = start; i <= end; i++)
            {
                //temp += its[i] + " ";
                if(type == "pre")
                {
                    t = its[i];
                    s = t.Substring(0, 1) + "-1" + t.Substring(1, 1) + "-2" + t.Substring(2, 1);
                }else if(type == "next")
                {
                    t = its[end - (i-start)];
                    s = t.Substring(0, 1) + "-1" + t.Substring(1, 1) + "-2" + t.Substring(2, 1);
                }
                else
                {
                    s = its[i];
                }
                if(check)
                	s = s.Replace("-",",");
                if (type == "null") {
                	if(check)
                		sw.Write(s+",");
                	else
	                	sw.Write(s + " ");
                }
                else sw.WriteLine(s);
            }

            // ---------------------
            sw.Close();
            fsw.Close();
            MessageBox.Show("导出完成！");
        }
		void Panel1Paint(object sender, PaintEventArgs e)
		{
	
		}
		void Button17Click(object sender, EventArgs e)
		{
			textBox6.Text = "";
		}

        private void richTextBox2_TextChanged(object sender, EventArgs e)
        {

        }
        /// <summary>
        /// 按照顺序次数计算
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCount_Click(object sender, EventArgs e)
        {
            FrmOrderCountDisplay frm = new FrmOrderCountDisplay();
            // 取得选中顺序次数
            if (cbOrderTime.SelectedItem == null)
            {
                MessageBox.Show("选中顺序次数为空，请重新选择", "提示");
            }
            string orderTime = (string)cbOrderTime.SelectedItem;
            string[] strTimes = orderTime.Trim().Split(' ');
            uint[] uScore = new uint[strTimes.Length];
            float[] fVlaue = new float[strTimes.Length];
            for (int i=0;i<strTimes.Length;i++)
            {
                foreach(DataGridViewRow row in dataGridView1.Rows)
                {
                    if(strTimes[i].Equals(row.Cells[1].Value))
                    {
                        uScore[i] = 1;
                        break;
                    }
                }
            }
            uint score = 0;
            uint sum = 0;
            for (int i = 0; i < strTimes.Length; i++)
            {
                if (uScore[i] > 0)
                {
                    score++;
                    uScore[i] = score;
                }
                sum += uScore[i];
            }
            for (int i = 0; i < strTimes.Length; i++)
            {
                if (uScore[i] > 0)
                {
                    fVlaue[i] = (uScore[i] * 10000 / sum) /100.0f; ;
                }
            }
            frm.LoadValue(strTimes, uScore, fVlaue);
            frm.ShowDialog();
        }
        /// <summary>
        /// 顺序次数设定
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSetOrderTime_Click(object sender, EventArgs e)
        {
            Form frm = new FrmOrderTime();
            DialogResult res = frm.ShowDialog();
            if(res == DialogResult.OK)
            {
                RefreshOrderTime();
            }
        }
        /// <summary>
        /// 刷新顺序次数 下拉框数据
        /// </summary>
        private void RefreshOrderTime()
        {
            // 读取顺序次数
            List<string> orderTimes = new List<string>();
            string strOrderTimeFilePath = Application.StartupPath + "//" + strOrderTimeFileName;
            if (File.Exists(strOrderTimeFilePath))
            {
                try
                {
                    string[] strOrderTimes = File.ReadAllLines(strOrderTimeFilePath);
                    orderTimes.AddRange(strOrderTimes);
                }
                finally
                {

                }
            }
            // 加载到下拉框
            string orderTime = (string)cbOrderTime.SelectedItem;
            cbOrderTime.Items.Clear();
            cbOrderTime.Items.AddRange(orderTimes.ToArray<string>());

            if (orderTime!=null && cbOrderTime.Items.Contains(orderTime))
            {
                cbOrderTime.SelectedItem = orderTime;
            }
            else
            {
                cbOrderTime.SelectedItem = null;
            }
        }
    }
}
